登录 白背景

leetcode/链表/剑指 Offer 18. 删除链表的节点.md

递归

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */
class Solution {

    /**
     * @param ListNode $head
     * @param Integer $val
     * @return ListNode
     */
    function deleteNode($head, $val) {
        if($head->val === $val){
            $ret = $head->next;
            unset($head);
            return $ret;
        }else{
            $head->next = $this->deleteNode($head->next, $val);
            return $head;
        }
    }
}

循环

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */
class Solution {

    /**
     * @param ListNode $head
     * @param Integer $val
     * @return ListNode
     */
    function deleteNode($head, $val) {
        $cur = $head;
        if($cur->val == $val){
            return $cur->next;
        }
        while(!empty($cur->next) && $cur->next->val !== $val){
            $cur = $cur->next;
        }
        if(!empty($cur->next)){
            $cur->next = $cur->next->next;
        }
        return $head;
    }
}